#include "stdafx.h"

extern WSASetLastError_proxy_t pTrueWSASetLastError;

int send_proxy ( 
    __in  SOCKET s,
    __in  const char*  buf,
    __in  int    len,
    __in  int    flags
    )
{
    try
    {
    //SEND
        Header header(GetCurrentThreadId(), "send");
        send_in_inout sendIN(s, buf, len, flags);
        
        std::vector<char> out_buffer;
        Serialize(header, sendIN, out_buffer);

        SendToClient (out_buffer);
        
    //RECEIVE()
        send_out_inout sendOUT;

        std::vector<char> in_buffer;
        
        RecvFromClient (in_buffer, header);
        Deserialize deserialize(in_buffer);
        deserialize(sendOUT);

        if(sendOUT.wsa_last_error_ != 0)
        {
            pTrueWSASetLastError(sendOUT.wsa_last_error_);
            return SOCKET_ERROR;
        }
        return sendOUT.ret_;
    }
    catch (std::exception& ex)
    {
        LOG(plog::error) << "send: " << ex.what();
    }
    pTrueWSASetLastError (WSAEWOULDBLOCK);
    return SOCKET_ERROR;
}

int sendto_proxy ( 
    __in  SOCKET s,
    __in  const char*  buf,
    __in  int    len,
    __in  int    flags,
    __in  const struct sockaddr* to,
    __in  int             tolen
    )
{
    try
    {
    //SEND
        Header header(GetCurrentThreadId(), "sendto");
        sendto_in_inout sendtoIN(s, buf, len, flags, to, tolen);
        
        std::vector<char> out_buffer;
        Serialize(header, sendtoIN, out_buffer);

        SendToClient (out_buffer);
        
    //RECEIVE()
        sendto_out_inout sendtoOUT;

        std::vector<char> in_buffer;
        
        RecvFromClient (in_buffer, header);
        Deserialize deserialize(in_buffer);
        deserialize(sendtoOUT);

        if(sendtoOUT.wsa_last_error_ != 0)
        {
            pTrueWSASetLastError(sendtoOUT.wsa_last_error_);
            return SOCKET_ERROR;
        }
        
        return sendtoOUT.ret_;
    }
    catch (std::exception& ex)
    {
        LOG(plog::error) << "sendto: " << ex.what();
    }
    pTrueWSASetLastError (WSAEWOULDBLOCK);
    return SOCKET_ERROR;
}
